/*************************初始化富文本编辑器**************************/
var ue = UE.getEditor('editor', {
    autoHeightEnabled: true,
    autoFloatEnabled: true,
    elementPathEnabled:false, // 隐藏元素路径
    initialFrameWidth: 1000,
    maximumWords: 10000,
    initialFrameHeight: 300,
    toolbars: [
        [
            'anchor', //锚点
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'indent', //首行缩进
            'italic', //斜体
            'underline', //下划线
            'strikethrough', //删除线
            'subscript', //下标
            'fontborder', //字符边框
            'superscript', //上标
            'formatmatch', //格式刷
            'source', //源代码
            'blockquote', //引用
            'pasteplain', //纯文本粘贴模式
            'selectall', //全选
            'preview', //预览
            'horizontal', //分隔线
            'removeformat', //清除格式
            'time', //时间
            'date', //日期
            'unlink', //取消链接
            'insertrow', //前插入行
            'insertcol', //前插入列
            'mergeright', //右合并单元格
            'mergedown', //下合并单元格
            'deleterow', //删除行
            'deletecol', //删除列
            'splittorows', //拆分成行
            'splittocols', //拆分成列
            'splittocells', //完全拆分单元格
            'deletecaption', //删除表格标题
            'inserttitle', //插入标题
            'mergecells', //合并多个单元格
            'deletetable', //删除表格
            'cleardoc', //清空文档
            'insertparagraphbeforetable', //"表格前插入行"
            'insertcode', //代码语言
            'fontfamily', //字体
            'fontsize', //字号
            'paragraph', //段落格式
            'edittable', //表格属性
            'edittd', //单元格属性
            'link', //超链接
            'emotion', //表情
            'spechars', //特殊字符
            'searchreplace', //查询替换
            'help', //帮助
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'backcolor', //背景色
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'fullscreen', //全屏
            'directionalityltr', //从左向右输入
            'directionalityrtl', //从右向左输入
            'rowspacingtop', //段前距
            'rowspacingbottom', //段后距
            'pagebreak', //分页
            'imagenone', //默认
            'imageleft', //左浮动
            'imageright', //右浮动
            'attachment', //附件
            'imagecenter', //居中
            'lineheight', //行间距
            'edittip ', //编辑提示
            'customstyle', //自定义标题
            'autotypeset', //自动排版
            'touppercase', //字母大写
            'tolowercase', //字母小写
            'template', //模板
            'scrawl', //涂鸦
            'inserttable', //插入表格
            'drafts', // 从草稿箱加载
            'charts', // 图表
        ]
    ]
});

ue.addListener('wordcountoverflow', function () {
    layer.msg("富文本内容过长,系统将自动删除超出字符!", {icon: 5, time: 3000});
    var chars = ue.getContentTxt();
    var schars = chars.substring(0, 10000);
    ue.setContent(schars);
});


UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
UE.Editor.prototype.getActionUrl = function (action) {
    if (action == 'uploadimage' || action == 'uploadvideo' || action == 'uploadfile') {
        return root.sroreinter.ueditor; //在这里返回我们实际的上传图片地址
    } else {
        return this._bkGetActionUrl.call(this, action);
    }
}

/*********************参数校验区****************************/
/*标题校验*/
$.validator.addMethod("titleCheck", function (value, element) {
    var tel = /^[A-Za-z0-9\u4e00-\u9fa5]{1,20}$/;
    return this.optional(element) || (tel.test(value));
}, "输入有误");

/*校验select*/
function validateSelect() {
    var val = $("#type").find("option:selected").val();
    if (val == 0) {
        layer.msg("请选择职位隶属!", {icon: 5, time: 3000});
        return false;
    }
    return true;
}

/*校验富文本内容*/
function validateUeditor(formData) {
    var flag = true;
    ue.ready(function () {
        //获取html内容，返回: <p>hello</p>
        var html = ue.getContentTxt();
        if (!html || html.length == 0) {
            layer.msg("职位描述内容不能为空!", {icon: 5, time: 3000});
            flag = false;
        }
        if (html.length > 10000) {
            layer.msg("职位描述内容过长!", {icon: 5, time: 3000});
            flag = false;
        }
        formData.append("description", ue.getContent());
    });
    return flag;
}

/***********************方法区***************************/
/*编辑 填充表单*/
$(function () {
    if (window.parent.recruitId != null) {
        $.ajax({
            url: root.sroreinter.get_recruitByid + '/' + window.parent.recruitId,
            type: "GET",
            headers: {'Content-Type': 'application/json'},
            success: function (data) {
                if (data) {
                    $("#title").val(data.title);
                    $("#type").val(data.type);
                    $("#release_time").val(data.release_time);
                    $("#expired_time").val(data.expired_time);
                    $("#number").val(data.number);
                    var saleAreaall=$("input:checkbox[name='saleArea']")
                    for(var k = 0; k < saleAreaall.length; k++) {
                        saleAreaall[k].checked = false;
                        var areaCode=data.address.split(",")
                        for(var i=0;areaCode.length>i;i++) {
                            if(areaCode[i]!=""){
                                if (areaCode[i] == saleAreaall[k].value) {
                                    saleAreaall[k].checked = true;
                                }
                            }

                        }
                    }
                    goodselectionall()
                    $("#contact_way ").val(data.contact_way);
                    /*填充富文本内容*/
                    if (data.description) {
                        ue.ready(function () {
                            ue.setContent(data.description);
                        });
                    }
                }
            }
        });
    }
});

// 表单提交
$("#form-add").validate({
    rules: {
        title: "titleCheck",

        custArea: {
            maxlength: 100
        },
        contact_way: {
            email: true
        },
        type
    },
    //提交表单数据
    submitHandler: function (form) {
        var areaLists=[]
        for(var i=0;$("input:checkbox[name='saleArea']:checked").length>i;i++) {
            areaLists.push($("input:checkbox[name='saleArea']:checked")[i].value)
        }
        if($("#title").val().trim()==""){
            $.Huimodalalert('请输入职位标题',2000);
            return false
        }
        if($("#number").val().trim()==""){
            $.Huimodalalert('请输入聘人数',2000);
            return false
        }

        var kks=$("#number").val()
        if(/[a-zA-Z]/.test(kks)){
            $.Huimodalalert('招聘人数不能输入字母',2000);
            return false
        }

        if(areaLists==""){
            $.Huimodalalert('请选择工作地址',2000);
            return false;
        }

        var loader = layer.load(0, {
            shade: [0.8, '#070002'] //0.1透明度的白色背景
        });


        var formData = new FormData();
        if (validateSelect()) {
            //校验富文本编辑器内容
            if (validateUeditor(formData)) {
                /*获取登陆信息*/
                var quzhi = JSON.parse(web.readCookie("loginData"))
                formData.append("title", $("#title").val());
                formData.append("type", $("#type").find("option:selected").val());
                formData.append("release_time", $('#release_time').val());
                formData.append("expired_time", $('#expired_time').val());
                formData.append("number", $("#number").val());
                formData.append("address", areaLists);
                formData.append("contact_way", $("#contact_way").val());
                /*数据入库*/
                if (window.parent.recruitId) {
                    formData.append("id", window.parent.recruitId);
                    formData.append("modifier_id", quzhi.user.user_ID);
                    formData.append("modifier_name", quzhi.user.username);
                    updateNews(formData);
                } else {
                    formData.append("creator_name", quzhi.user.username);
                    formData.append("creator_id", quzhi.user.user_ID);
                    addNews(formData);
                }
            }
        }
        setTimeout(function () {
            layer.close(loader);
        }, 3000);
    }
})


/*新增新闻信息*/
function addNews(formData) {
    $.ajax({
        url: root.sroreinter.add_recruit,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        async: false,
        data: formData,
        success: function (data) {
            if (data.errorCode == 0) {
                layer.msg(data.errorMessage, {icon: 6, time: 3000});
                setTimeout(function () {
                    parent.comPageNum = 1;
                    parent.seahsdfs(1);
                    removeIframe();
                }, 3000);
            } else {
                layer.msg(data.errorMessage, {icon: 5, time: 3000});
            }
        }
    });
}

/*更新招聘信息*/
function updateNews(formData) {
    $.ajax({
        url: root.sroreinter.update_recruit,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData: false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType: false,
        async: false,
        data: formData,
        success: function (data) {
            if (data.errorCode == 0) {
                layer.msg(data.errorMessage, {icon: 6, time: 3000});
                setTimeout(function () {
                    parent.seahsdfs(parent.comPageNum);
                    removeIframe();
                }, 3000);
            } else {
                layer.msg(data.errorMessage, {icon: 5, time: 3000});
            }
        }
    });
}


/*关闭详情页*/
function removeIframe() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

$.ajax({
    contentType: "application/json;charset=UTF-8",
    url: root.publics.queryWarehouseInfo,
    cache: false, //禁用缓存
    type: "POST",
    dataType:"json",
    async:false,//优先运行
    data: JSON.stringify({
        warehouseCode:""

    }),
    success: function(data){
        var RegionSelection2 =""
        $.each(data.data,function(k,v){
            if(v.warehouseDataType !=2){
            RegionSelection2+='<label style="float: left;"><input type="checkbox" onclick="goodselectionall()" value='+v.warehouseAliasName+' checked="checked" name="saleArea"/>'+v.warehouseAliasName+'&nbsp;&nbsp;</label>'
        }
        })
        $("#RegionSelection2").html(RegionSelection2)


    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log(XMLHttpRequest);
    }
});
//全选全不选
function goodselection() {
    if($("#saleAreas").is(':checked')==true){
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = true;
        }
    }else {
        var saleArea=$("input:checkbox[name='saleArea']")
        for(var i = 0; i < saleArea.length; i++) {
            saleArea[i].checked = false;
        }
    }

}
//子级选中
goodselectionall()
function goodselectionall() {
    var saleArea=$("input:checkbox[name='saleArea']")
    var saleArea2=$("input:checkbox[name='saleArea']:checked")
    if(saleArea2.length==saleArea.length){
        $("#saleAreas").prop("checked", true)
    }else {
        $("#saleAreas").prop("checked", false)
    }
}